<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getPersmissionListApi, delPermissionApi } from '@/api/permission'
import type { PermissionItem } from '@/types/permission'
import { transListToTreeData } from '@/utils/index'
import { ElMessageBox, ElMessage } from 'element-plus'
// @ts-ignore
import addPermission from './components/add-permission.vue'

// 获取权限列表
const permissionList = ref<PermissionItem[]>()

const getPermissionList = async () => {
  const res = await getPersmissionListApi()
  // 将平铺数据 转换成树状结构
  permissionList.value = transListToTreeData<PermissionItem>(res.data, '0')
}

// 删除权限
const delPermission = async (id: string) => {
  // 提示用户 是否删除
  await ElMessageBox.confirm('此操作将永久删除该文件，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  // 调用删除接口
  await delPermissionApi(id)
  // 提示用户
  ElMessage.success('删除成功')
  // 重新获取数据
  getPermissionList()
}

//控制弹框隐藏展示
const addPermissionRef = ref<InstanceType<typeof addPermission> | null>(null)

// 添加权限
const AddPermissions = (id: string, type: 1 | 2) => {
  addPermissionRef.value?.openDialog(id, type)
}

// 编辑权限

const editPermission = async (id: string) => {
  // 获取权限详情
  addPermissionRef.value?.getPermissionDetail(id)
}

onMounted(() => {
  getPermissionList()
})
</script>

<template>
  <div class="permssion-container">
    <div class="app-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <el-button type="primary" @click="AddPermissions('0', 1)">添加权限</el-button>
          </div>
        </template>
        <el-table style="width: 100%; margin-bottom: 20px" default-expand-all :data="permissionList" row-key="id">
          <el-table-column label="菜单名称" prop="name" />
          <el-table-column label="权限标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button text type="primary" v-if="row.type === 1" @click="AddPermissions(row.id, 2)">添加权限点</el-button>
              <el-button text type="primary" @click="editPermission(row.id)">编辑</el-button>
              <el-button text type="primary" @click="delPermission(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- dialog 弹框组件 -->
      <add-permission ref="addPermissionRef" @updataList="getPermissionList"></add-permission>
    </div>
  </div>
</template>
<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: flex-end;
}
</style>
